package com.socket.secure.core;

import com.socket.secure.constant.RequsetTemplate;
import com.socket.secure.exception.InvalidRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Secure Transmission Handler
 */
@RestController
public class SecureHandler {
    private SecureCore secureCore;

    @GetMapping("/secure/favicon.ico")
    private void syncPubkey(HttpServletResponse response) throws IOException {
        secureCore.syncPubkey(response);
    }

    @PostMapping("/secure/exchange")
    private String syncAeskey(@RequestBody String certificate, HttpServletRequest request) {
        String signature = request.getHeader("signature");
        final int SIGN_SIZE = 224, SUB_INDEX = 96;
        if (signature != null && signature.length() == SIGN_SIZE) {
            String key = signature.substring(0, SUB_INDEX);
            String digest = signature.substring(SUB_INDEX);
            return secureCore.syncAeskey(certificate, key, digest);
        }
        throw new InvalidRequestException(RequsetTemplate.INVALID_HEADER_SIGNATURE);
    }

    @Autowired
    public void setSecureCore(SecureCore secureCore) {
        this.secureCore = secureCore;
    }
}
